<?php

declare(strict_types=1);

namespace app\model;

use app\agent\model\UserWithdraw;
use think\Exception;
use think\facade\Db;
use think\facade\Log;

/**
 * 
 *
 * @mixin \think\Model
 * @property int $id 自增id
 * @property int $agent_id 代理商id
 * @property int $amount 提现金额。单位：分
 * @property int $charge 提现手续费。单位：分
 * @property int $real_price 实际提现金额：扣除手续费之后的金额。单位：分
 * @property string $alipay 支付宝账号
 * @property string $mobile 手机号码
 * @property string $wechat 微信号
 * @property int $status 状态：1待审核 2审核通过 3已拒绝 4已撤销 5打款失败 6已打款
 * @property string $remark 备注信息
 * @property string $created_at 创建时间
 * @property string $updated_at 更新时间
 * @property int $type 提现方式：1支付宝 2银行卡
 * @property string $bank_card_no 银行卡号
 * @property string $bank_username 银行卡户名
 * @property string $bank_name 开户行
 * @property string $user_remark 用户备注
 * @property-read \app\model\Agent $agent
 * @property bool $from 发起提现1 惠充平台 2 有美生活
 * @property-read \app\model\AgentExtend $agent_extend
 */
class AgentWithdraw extends CommonModel
{

    const STATUS_WAIT = 1;
    const STATUS_PASS = 2;
    const STATUS_SUCCESS = 6;

    const FROM_HUICHONG = 1;
    const FROM_YMSH = 2;
    /*
     状态管理 请同步维护数据库备注
    */
    public static $status = [
        1 => '待审核',
        2 => '已通过',
        3 => '已拒绝',
        4 => '已撤销',
        5 => '打款失败',
        6 => '已打款',
    ];


    public function agent()
    {
        return $this->hasOne(Agent::class, 'id','agent_id');
    }

    public function agentExtend()
    {
        return $this->hasOne(AgentExtend::class, 'agent_id','agent_id');
    }

    /**
     * 发起提现
     */
    public static function onAfterInsert($userWithdraw){

        /**
         * @var self $userWithdraw
         */
        $agent = $userWithdraw->agent;


        $updateAgent = Agent::where('id',$userWithdraw->agent_id)
            ->whereRaw("`profit_balance`- :amount >= 0",['amount' => $userWithdraw->amount])
            ->dec('profit_balance',$userWithdraw->amount)
            ->inc('withdraw_amount',$userWithdraw->amount)
            ->update(['balance_last_updated_at' => date('Y-m-d H:i:s'),]);

        if (!$updateAgent){
            $msg = '提现余额不足 agent_id:'.$userWithdraw->agent_id.'当前代理商余额为：'.$agent->profit_balance;
            Log::error($msg);
            throw new Exception($msg);
        }

        /**
         * 佣金记录
         */
        AgentBalanceLog::create([
                'agent_id' => $userWithdraw->agent_id,
                'type' => BALANCE_WITHDRAW_APPLY,
                'amount' => - $userWithdraw->amount,
                'old_balance' => $agent->profit_balance,
                'new_balance' => $agent->profit_balance - $userWithdraw->amount,
                'remark' => '提现'.fen2yuan($userWithdraw->amount),
                'quote_id' => $userWithdraw->id,
            ]);

    }

}
